//
//  MWAppealViewController.swift
//  mggz
//
//  Created by QinWei on 2018/4/7.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import MobileCoreServices
import TZImagePickerController
class MWAppealViewController: UIViewController {
    var form:[String: Any]?
    var startTime:String?
    var endTime:String?
    fileprivate var inforationArray:NSMutableArray?
    fileprivate var backInfoArray:NSMutableArray?
    @IBOutlet weak var posiveHeight: NSLayoutConstraint!
    
    @IBOutlet weak var nagativeHeight: NSLayoutConstraint!
    @IBOutlet weak var headerButton: UIButton!
    
    @IBOutlet weak var nagativeButton: UIButton!
   
    
    @IBOutlet weak var potiveButton: UIButton!
    
    fileprivate var positiveIcon:UIImage?
    fileprivate var headerImage:UIImage?
    fileprivate var nagativeIcon:UIImage?
    var timeAlert:TWLAlertView?
    override func viewDidLoad() {
        super.viewDidLoad()
        
        AipOcrService.shard().auth(withAK: BaiduYunAPIKey, andSK: BaiduYunSecretKey)
       self.posiveHeight.constant = 150*SCREEN_WIDTH/320
       self.nagativeHeight.constant = 150*SCREEN_WIDTH/320
        
    }
    
    
    @IBAction func headerButtonClick(_ sender: Any) {
        var responder = self.next
        while !(responder is UIViewController) {
            responder = responder?.next
        }
        if responder is UIViewController {
            let vc = responder as! UIViewController
            
            let tool = PhotoSheet()
            tool.showCTOnlyPhotoSheet(viewController: vc) { [unowned self](images) in
                if images != nil && images!.count > 0 {
                    self.headerImage = images![0]
                    self.headerButton.setImage(images![0], for: UIControlState.normal)
                }
            }
            
        }
    }
    
    
    @IBAction func positiveButtonClick(_ sender: Any) {
        let ocrVc = AipCaptureCardVC.viewController(with: .localIdCardFont) { (ocrImage) in
            AipOcrService.shard().detectIdCardFront(from: ocrImage, withOptions: nil, successHandler: { (result) in
                
                DispatchQueue.main.async {
                    self.setupResultWithUI(result as! [String : AnyObject])
                    self.potiveButton.setImage(ocrImage, for: .normal)
                    self.positiveIcon = ocrImage
                    self.dismiss(animated: true, completion: {
                       
                        
                    })
                }
            }, failHandler: { (error) in
                
            })
        }
        
        self.present(ocrVc!, animated: true) {
            
        }
        
    }
    
    fileprivate func setupResultWithUI(_ result:[String:AnyObject]){
        self.inforationArray = NSMutableArray.init()
        if (result["words_result"] != nil){
            (result["words_result"])?.enumerateKeysAndObjects({ (mykey, myObj, myStop) in
                guard let selectObj : NSDictionary = myObj as? NSDictionary else{
                    return
                }
                if let selectWord = selectObj["words"] {
                    self.inforationArray?.add(selectWord)
                }else{
                    return
                }
            })
        }else{
            
        }
        
        let userAge = self.switchDateToAge(self.inforationArray![1] as! String)
        self.inforationArray?.replaceObject(at: 1, with: userAge)
        
    }
    fileprivate func switchDateToAge(_ year:String) -> String{
        
        let formate = DateFormatter()
        formate.dateFormat = "yyyyMMdd"
        let date = formate.date(from: year)
        let currentDate = NSDate()
        let time = currentDate.timeIntervalSince(date!)
        let age = Int(time)/(3600*24*365)
        return String(age)
        
    }
    
    @IBAction func nagativeButtonClick(_ sender: Any) {
        let ocrVc = AipCaptureCardVC.viewController(with: .localIdCardBack) { (ocrImage) in
            AipOcrService.shard().detectIdCardBack(from: ocrImage, withOptions: nil, successHandler: { (result) in
                DispatchQueue.main.async {
                    self.setupNagativeResultWithUI(result as! [String : AnyObject])
                    self.dismiss(animated: true, completion: {
                        
                    })
                    
                    self.nagativeButton.setImage(ocrImage, for: .normal)
                    self.nagativeIcon = ocrImage
                    
                }
            }, failHandler: { (error) in
                
            })
        }
        
        self.present(ocrVc!, animated: true) {
            
        }
    }
    

    fileprivate func dealWithTime(_ backArray:NSMutableArray){
        
        guard var firstTime = backArray[1] as? String else {
            return
        }
        guard var secondTime = backArray[0] as? String else {
            return
        }
        
        
        firstTime.insert("-", at: (firstTime.index((firstTime.startIndex), offsetBy: 4)))
        
        firstTime.insert("-", at: (firstTime.index((firstTime.startIndex), offsetBy: 7)))
        if secondTime.count > 7 {
            
            secondTime.insert("-", at: (secondTime.index((secondTime.startIndex), offsetBy: 4)))
            secondTime.insert("-", at: (secondTime.index((secondTime.startIndex), offsetBy: 7)))
            
        }
        self.startTime = firstTime
        self.endTime = secondTime
       // self.legalDate.text = firstTime + "至" + secondTime
    }
    fileprivate func setupNagativeResultWithUI(_ result:[String:AnyObject]){
        
        self.backInfoArray = NSMutableArray.init()
        if (result["words_result"] != nil){
            (result["words_result"])?.enumerateKeysAndObjects({ (mykey, myObj, myStop) in
                guard let selectObj : NSDictionary = myObj as? NSDictionary else{
                    return
                }
                
                if let selectWord = selectObj["words"] {
                    self.backInfoArray?.add(selectWord)
                    
                }else{
                    return
                }
            })
        }else{
            
        }
        self.dealWithTime(self.backInfoArray!)
        
    }
    
    @IBAction func submitButtonClick(_ sender: Any) {
        guard (self.nagativeIcon != nil) else {
            QWTextonlyHud("身份证反面未扫描", target: self.view)
            return
        }
        guard (self.positiveIcon != nil) else {
            QWTextonlyHud("身份证正面未扫描", target: self.view)
            return
        }
        guard (self.startTime != nil) else {
            QWTextonlyHud("数据不完整", target: self.view)
            return
        }
        guard (self.endTime != nil) else {
            QWTextonlyHud("数据不完整", target: self.view)
            return
        }
        if (self.endTime?.count)! > Int(8){
            let cardDate = stringToDate(dateString: self.endTime!)
            if cardDate! < Date(){
                QWTextonlyHud("身份证已过期，请拍摄有效的身份证", target: self.view)
                return
            }
        }
        
        guard let name : String = self.inforationArray![0] as? String,name != "" else{
            QWTextonlyHud("姓名不完全,请重新扫描", target: self.view)
            return
        }
        guard let ageLabel : String = self.inforationArray![1] as? String,ageLabel != "" else{
            QWTextonlyHud("年龄不完全,请重新扫描", target: self.view)
            return
        }
        guard let idCardLabel : String = self.inforationArray![2] as? String,idCardLabel != "" else{
            QWTextonlyHud("身份证不完全,请重新扫描", target: self.view)
            return
        }
        guard let sexLabel : String = self.inforationArray![3] as? String,sexLabel != "" else{
            QWTextonlyHud("性别不完全,请重新扫描", target: self.view)
            return
        }
        guard let detailLabel : String = self.inforationArray![3] as? String,detailLabel != "" else{
            QWTextonlyHud("地址不完全,请重新扫描", target: self.view)
            return
        }
        
        self.timeAlert = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        let custom : CTApplicationView = CTApplicationView.init(frame: CGRect(x: 0, y: 0, width: 250, height: 130))
        custom.applicationButton.addTarget(self, action: #selector(applicationAllInfoClick), for: .touchUpInside)
        custom.cancelButton.addTarget(self, action: #selector(cancelButtonClick), for: .touchUpInside)
        self.timeAlert?.initWithCustomView(custom, frame: CGRect(x: 0, y: 0, width: 250, height: 130))
        let keyWindow = UIApplication.shared.keyWindow
        keyWindow?.addSubview(self.timeAlert!)
        
    }
    @objc fileprivate func applicationAllInfoClick(){
        self.timeAlert?.cancleView()
        
        
        
        
    }
    @objc fileprivate func cancelButtonClick(){
        self.timeAlert?.cancleView()
    }
}
